package com.example.netty;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @author shanchong
 * @date 2021/3/21
 **/
public class MyConsole {

    public static void run(ChannelFuture channelFuture) {
        String prompt = "command> ";
        try {
            Terminal terminal = TerminalBuilder.builder()
                    .streams(System.in, System.out)
                    .system(false)
                    .build();
            LineReader lineReader = LineReaderBuilder.builder()
                    .terminal(terminal)
                    .build();
            channelFuture.channel().pipeline().addLast(new SimpleChannelInboundHandler() {
                @Override
                public void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
                    terminal.writer().print(msg);
                    String line = lineReader.readLine(prompt);
                    channelFuture.channel().writeAndFlush(line);
                }
            });
            String line = lineReader.readLine(prompt);
            channelFuture.channel().writeAndFlush(line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
